package com.ysstech.finance.controller;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.finance.entity.*;
import com.ysstech.finance.enums.FinanceEnum;
import com.ysstech.finance.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2021-03-10
 */
@Controller
@Slf4j
@Api(tags = "科目管理api")
@RequestMapping("/subject")
public class SubjectController extends BaseController {

    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SubjectProjectService subjectProjectService;
    @Autowired
    private SubjectAdjustAuxilaryService subjectAdjustAuxilaryService;
    @Autowired
    private SubjectSubjectAuxilaryService subjectSubjectAuxilaryService;

    @YssPermissions(value = {"finance:subject"})
    @ApiOperation(value = "跳转科目管理页面")
    @YssLog(module = "科目管理", remark = "跳转科目管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "finance/subject";
    }


    @YssPermissions(value = {"finance:subject"})
    @ApiOperation(value = "获取科目页面初始值")
    @YssLog(module = "科目管理", remark = "获取科目页面初始值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        List<Dicvalue> assetsType = dicValueService.getCacheDicValueList(FinanceEnum.ASSETSTYPE_CODE.getCode());
        map.put("assetsType", assetsType);
        map.put("assetsType2", assetsType);
        List<SubjectProject> list = subjectProjectService.list();
        map.put("listProject", list);
        // 科目核算项
        List<Dicvalue> adjustCode = dicValueService.getCacheDicValueList(FinanceEnum.ADJUST_CODE.getCode());
        map.put("adjustCode", adjustCode);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    /**
     * 获取科目信息
     *
     * @return
     */
    @YssPermissions(value = {"finance:subject"})
    @ApiOperation(value = "获取科目信息")
    @YssLog(module = "科目管理", remark = "获取科目信息")
    @PostMapping(value = "/querySubjectTree")
    @ResponseBody
    public RestResult querySubjectTree(Subject subject) throws Exception {
        return ResultGenerator.getSuccessResult("获取科目信息成功", subjectService.querySubjectTree(subject));
    }


    /**
     * 获取一个科目信息
     *
     * @return
     */
    @YssPermissions(value = {"finance:subject"})
    @ApiOperation(value = "获取科目信息")
    @YssLog(module = "科目管理", remark = "获取科目信息")
    @PostMapping(value = "/querySubject")
    @ResponseBody
    public RestResult querySubject(Subject subject) throws Exception {
        if (null == subject || StringUtils.isBlank(subject.getId())) {
            return ResultGenerator.getFailResult("检查科目代码失败，请稍后重试！");
        }
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("ID", subject.getId());
        return ResultGenerator.getSuccessResult("获取科目信息成功", subjectService.getOne(wrapper));
    }

    /**
     * 判断用表名称是否已经存在
     *
     * @param subject
     * @return
     */
    @ApiOperation(value = "检查科目代码是否存在")
    @YssLog(module = "科目管理", remark = "检查科目代码是否存在")
    @RequestMapping(value = "/checkCode")
    @ResponseBody
    public RestResult checkCode(Subject subject) {
        if (null == subject || StringUtils.isBlank(subject.getCode())
                || StringUtils.isBlank(subject.getProjectId())) {
            return ResultGenerator.getFailResult("检查科目代码失败，请稍后重试！");
        }
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("CODE", subject.getCode());
        wrapper.eq("PROJECT_ID", subject.getProjectId());
        int count = subjectService.count(wrapper);
        //查询是否存在code值得参数
        if (count > 0) {//返回true表示已经存在
            return ResultGenerator.getSuccessResult("检查科目代码信息成功", false);
        } else {
            return ResultGenerator.getSuccessResult("检查科目代码信息成功", true);
        }
    }

    /**
     * 新增科目条目信息
     *
     * @return
     */
    @YssPermissions(value = {"finance:subject:add"})
    @ApiOperation(value = "新增科目信息")
    @YssLog(module = "科目管理", remark = "新增科目信息")
    @RequestMapping(value = "/addSubject")
    @ResponseBody
    public RestResult addSubject(Subject subject) throws Exception {
        if (subject == null) {
            throw new BusinessException("获取科目信息失败，请稍后重试！");
        }
        subject.setId(DateUtil.generateUUID());
        subject.setAddTime(LocalDateTime.now());
        subject.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        subjectService.save(subject);
        addSubjectSubjectAuxilary(subject);
        return ResultGenerator.getSuccessResult("新增科目条目信息成功！");
    }

    /**
     * 修改科目条目信息
     *
     * @return
     */
    @YssPermissions(value = {"finance:subject:edit"})
    @ApiOperation(value = "修改科目信息")
    @YssLog(module = "科目管理", remark = "修改科目信息")
    @RequestMapping(value = "/editSubject")
    @ResponseBody
    public RestResult editSubject(Subject subject) throws Exception {
        if (subject == null || StringUtils.isBlank(subject.getId())) {
            throw new BusinessException("获取科目信息失败，请稍后重试！");
        }
        subjectService.updateById(subject);
        addSubjectSubjectAuxilary(subject);
        return ResultGenerator.getSuccessResult("修改科目条目信息成功！");
    }

    /**
     * 保存科目辅助项关系信息
     *
     * @param subject
     * @throws Exception
     */
    private void addSubjectSubjectAuxilary(Subject subject) throws Exception {
        // 获取页面选中的值信息
        List<String> list = JSONArray.parseArray(subject.getSubjectAuxilary(), String.class);
        if (!CollectionUtils.isEmpty(list) && list.size() > 1) {
            //获取核算项对应的辅助项集合
            SubjectAdjustAuxilary subjectAdjustAuxilary = new SubjectAdjustAuxilary();
            subjectAdjustAuxilary.setProjectId(subject.getProjectId());
            subjectAdjustAuxilary.setSubjectId(subject.getId());
            QueryWrapper<SubjectAdjustAuxilary> wrapper = new QueryWrapper<>();
            wrapper.eq("ADJUST_CODE", subject.getAdjustCode());
            wrapper.eq("PROJECT_ID", subject.getProjectId());
            List<SubjectAdjustAuxilary> subjectAuxilaries = subjectAdjustAuxilaryService.list(wrapper);
            if (CollectionUtils.isEmpty(subjectAuxilaries)) {
                return;
            }
            List<SubjectSubjectAuxilary> updatelist = new ArrayList<>();
            // 新增科目和辅助项关联关系
            for (int i = 0; i < subjectAuxilaries.size(); i++) {
                SubjectAdjustAuxilary auxilary = subjectAuxilaries.get(i);
                if (null == auxilary) {
                    continue;
                }
                SubjectSubjectAuxilary subjectSubjectAuxilary = new SubjectSubjectAuxilary();
                subjectSubjectAuxilary.setId(DateUtil.generateUUID());
                subjectSubjectAuxilary.setSubjectId(subject.getId());
                subjectSubjectAuxilary.setAdjustCode(subject.getAdjustCode());
                subjectSubjectAuxilary.setAuxilaryCode(auxilary.getAuxilaryCode());
                subjectSubjectAuxilary.setAuxilaryValue(list.get(i));
                subjectSubjectAuxilary.setProjectId(subject.getProjectId());
                updatelist.add(subjectSubjectAuxilary);
            }
            subjectSubjectAuxilaryService.saveBatch(updatelist);
        }
    }

    /**
     * 删除科目信息
     *
     * @return
     */
    @YssPermissions(value = {"finance:subject:del"})
    @ApiOperation(value = "删除科目信息")
    @YssLog(module = "科目信息管理", remark = "删除科目信息信息")
    @RequestMapping(value = "/delSubject")
    @ResponseBody
    public RestResult delSubject(Subject subject) throws Exception {
        if (null == subject || StringUtils.isBlank(subject.getId())) {
            throw new BusinessException("获取删除科目信息失败，请稍后重试！");
        }
        //获取所有下级的科目
        List<String> listDel = new ArrayList<>();
        listDel.add(subject.getId());
        // 获取科目下的所有下级科目
        subject.setParentId(subject.getId());
        List<TreeNode> nodeList = subjectService.querySubjectTree(subject);
        getChilderList(nodeList, listDel);
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.in("ID", listDel);
        subjectService.remove(wrapper);
        //删除科目辅助项关系信息
        QueryWrapper<SubjectSubjectAuxilary> wrapper2 = new QueryWrapper<>();
        wrapper2.in("SUBJECT_ID", listDel);
        subjectSubjectAuxilaryService.remove(wrapper2);
        return ResultGenerator.getSuccessResult("删除科目信息成功！");
    }


    public void getChilderList(List<TreeNode> nodeList, List<String> listDel) throws Exception {
        for (TreeNode node : nodeList) {
            if (null == node) {
                continue;
            }
            List<TreeNode> children = node.getChildren();
            if (CollectionUtils.isEmpty(children)) {
                return;
            }
            listDel.add(node.getId());
            for (TreeNode treeNode : children) {
                listDel.add(treeNode.getId());
            }
            getChilderList(children, listDel);
        }
    }

    /**
     * 提供外部接口查询科目信息
     *
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取科目信息")
    @YssLog(module = "科目信息管理", remark = "获取科目信息信息")
    @RequestMapping(value = "/getSubjectMap")
    @ResponseBody
    public Map<String, Subject> getSubjectMap() throws Exception {
        return subjectService.getSubjectMap();
    }
}
